<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Wechat;
use app\common\model\Approves;
use app\common\model\Tasks;
use app\common\model\User;
use app\common\model\UserOauth;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Hook;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $group_id = 1;

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */

    //完善订单时效
    public function task_range()
    {
        $task_list = Tasks::order('id', 'desc')->select();
        Db::startTrans();
        try {
            foreach ($task_list as $list) {
                $create_time = $list->createtime;
                if ($list->edittime){
                    $create_time = $list->edittime;
                }
                //接单时效：从任务发起 — 接单
                if (isset($list->ext_arr['take_time'])) {
                    $list->take_range = $list->ext_arr['take_time'] - $create_time;
                }
                //取件时效：从取件 — 取件送达
                if (isset($list->ext_arr['pick_time']) && isset($list->ext_arr['deliver_time'])) {
                    $list->pick_range = $list->ext_arr['deliver_time'] - $list->ext_arr['pick_time'];
                }
                //维修时效：从维修 — 维修完成
                if (isset($list->ext_arr['service_start_time']) && isset($list->ext_arr['serviced_time'])) {
                    $list->service_range = $list->ext_arr['serviced_time'] - $list->ext_arr['service_start_time'];
                }
                if ($list->service_status == -1){
                    if (isset($list->ext_arr['deliver_time']) && isset($list->ext_arr['serviced_time'])) {
                        $list->service_range = $list->ext_arr['serviced_time'] - $list->ext_arr['pick_time'];
                    }
                }
                //还件时效：从维修完成 — 还件成功
                if (isset($list->ext_arr['serviced_time']) && isset($list->ext_arr['return_time'])) {
                    $list->return_range = $list->ext_arr['return_time'] - $list->ext_arr['serviced_time'];
                }
                //取件用时：从接单 — 取件
                if (isset($list->ext_arr['pick_time']) && isset($list->ext_arr['take_time'])) {
                    $list->take_pick_range = $list->ext_arr['pick_time'] - $list->ext_arr['take_time'];
                }
                //维修准备用时：从取件送达 — 开始维修
                if (isset($list->ext_arr['deliver_time']) && isset($list->ext_arr['service_start_time'])) {
                    $list->pick_service_range = $list->ext_arr['service_start_time'] - $list->ext_arr['deliver_time'];
                }
                //任务总时效：从发起 — 至结束或取消
                if (isset($list->ext_arr['return_time'])) {
                    $list->finishtime = $list->ext_arr['return_time'];
                    $list->range = $list->ext_arr['return_time'] - $create_time;
                }
                $list->save();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error(__($e->getMessage()));
        }
        $this->success('ok', $task_list);
    }

    public function access_token()
    {
        $wechat = new Wechat('wxOfficialAccount');
        $access_token = $wechat->getAccessToken();
        $this->success('ok',$access_token);
    }

    public function getAdmin()
    {
        $user_ids = User::where('FIND_IN_SET('.$this->group_id.',group_ids)')->column('id');
        if (!$user_ids){
            //如果不存在
            dp('没有超级管理员');
        }
        $openids = UserOauth::whereIn('user_id',$user_ids)->column('openid');
        foreach ($openids as $openid){
            var_dump($openid);
        }
    }

    public function orderSN()
    {
        $tasks = Db::name('tasks')->select();
        foreach ($tasks as $task){
            if (!$task['order_sn']){
                Db::name('tasks')->where(['id'=>$task['id']])->update(['order_sn'=>Tasks::getSn($task['user_id'])]);
            }
        }
        $this->success('ok',$tasks);
        dp($tasks);
    }

    public function test()
    {
        $data['task'] = Tasks::where('id',55)->find();
        $data['action'] = 'created';

        Hook::listen('send_message',$data);

        $this->success('发送任务消息');
    }

    public function test1()
    {
        $data['approve'] = Approves::where('id',26)->find();
        $data['action'] = 'refuse';
        //发微信通知
        Hook::listen('send_sp_message',$data);
        $this->success('发送审批消息');
    }

    public function test2()
    {
        $data['backlog'] = \app\common\model\Backlog::where('id',1)->find();
        $data['action'] = 'success';
        //发微信通知
        Hook::listen('send_work_message',$data);
        $this->success('发送仪事消息');
    }

    public function send()
    {
        $wechat = new Wechat('wxOfficialAccount');

        $templateId = "ZiQpXe9BVAMTt2Elr1MknS1UZi0hq7zKIrUV3cidPC8";
        $openid = "oAovl63FF2SL4eLsqEF2zhqHUu58";

        $data = [
            "character_string7" => ["value"=>"1111",],
            "thing13" => ["value"=>"小鱼",],
            "time14" => ["value"=>"2023-05-06",],
            "time4" => ["value"=>"2022-12-28 17:00",],
        ];

        $messageData = [
            "openId" => $openid,
            "templateId" => $templateId,
            "page" => 'pages/index/index',
            "formId"   => "MSG_000003",
            "data" => $data
        ];
        $result = $wechat->sendTemplateMessage($messageData);
        dp($result);
    }


    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

}
